// #include <iostream>
// #include <string.h>
// #include <unistd.h>
// #include <pthread.h>

// pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// void* active(void* args)
// {
//     std::string name = static_cast<const char*>(args);
//     while(true)
//     {
//         pthread_mutex_lock(&mutex);
//         pthread_cond_wait(&cond, &mutex);
//         std::cout<< name << "活动..." << std::endl;
//         pthread_mutex_unlock(&mutex);
//     }
// }

// int main()
// {
//     pthread_t t1, t2;

//     pthread_create(&t1, nullptr, active, (void*)"thread -1");
//     pthread_create(&t2, nullptr, active, (void*)"thread -2");

//     sleep(3);
//     while(true)
//     {
//         //对比测试
//         pthread_cond_signal(&cond);//唤醒一个线程
//         // pthread_cond_broadcast(&cond);//唤醒所有线程
//         sleep(1);

//     }

//     pthread_join(t1, nullptr);
//     pthread_join(t2, nullptr);

//     pthread_cond_destroy(&cond);
//     pthread_mutex_destroy(&mutex);
//     return 0;
// }

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>

int ticket = 0;
pthread_mutex_t mutex;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *Routine(void *args)
{
    char *id = (char *)args;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", id, ticket);
            ticket--;
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            printf("%s wait on cond!\n", id);
            pthread_cond_wait(&cond, &mutex); // 醒来的时候， 会重新申请锁！！
            printf("%s, 被叫醒了\n", id);
        }
        pthread_mutex_unlock(&mutex);
    }

    return nullptr;
}

int main()
{
    pthread_t t1, t2, t3, t4;
    pthread_mutex_init(&mutex, nullptr);

    pthread_create(&t1, nullptr, Routine, (void *)"thread -1");
    pthread_create(&t2, nullptr, Routine, (void *)"thread -2");
    pthread_create(&t3, nullptr, Routine, (void *)"thread -3");
    pthread_create(&t4, nullptr, Routine, (void *)"thread -4");

    int cnt = 10;

    while (true)
    {
        sleep(5);
        ticket += cnt;
        printf("主线程放票喽， ticket: %d\n", ticket);
        pthread_cond_signal(&cond);
    }

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);


    return 0;
}